import React, { useState } from 'react'

import axios from 'axios'
import PubSub from 'pubsub-js'

export default function Header() {

  const [search, setSearch] = useState('')

  const iptChangeHandler = (e) => {
    setSearch(e.target.value)
  }

  const searchBtnHandler = async () => {
    PubSub.publish("github", { isInit: false, isSearch: true, data: [] })
    try {
      const result = await axios.get(`https://api.github.com/search/users?q=${search}`)
      PubSub.publish("github", { isInit: false, isSearch: false, data: result.data.items })
      console.log(result);
    } catch (error) {
      console.log(error);
    }
  }

  return (
    <section className="jumbotron">
      <h3 className="jumbotron-heading">Search Github Users</h3>
      <div>
        <input
          type="text" 
          value={search} 
          onChange={iptChangeHandler}  
          placeholder="enter the name you search" 
        />&nbsp;<button onClick={searchBtnHandler}>Search</button>
      </div>
    </section>
  )
}
